package cn.shujuhai.qtadmin.platform.service.impl;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.date.DateUtil;
import cn.shujuhai.qtadmin.platform.domain.SysLogging;
import cn.shujuhai.qtadmin.platform.mapper.SysLoggingMapper;
import cn.shujuhai.qtadmin.platform.service.SysLoggingService;
import lombok.extern.slf4j.Slf4j;

/**
 * @author dch
 */
@Slf4j
@Service
public class SysLoggingServiceImpl extends BaseServiceImpl<SysLoggingMapper, SysLogging> implements SysLoggingService {

    /**
     * 备份数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 1 * * ?")
    public void bakCurrentDatas() {
        log.info("定时备份任务开始......");
        String tableName = "sys_logging_bak_" + DateUtil.format(DateUtil.date(), "yyyyMM");
        if (!tableName.equals(this.baseMapper.checkTableExistsWithSchema(tableName))) {
            this.baseMapper.createBakTable(tableName);
        }
        var dateTime = DateUtil.endOfDay(DateUtil.lastMonth());
        this.baseMapper.bakCurrentDatas(tableName, dateTime);
        this.remove(new QueryWrapper<SysLogging>().lt("create_time", dateTime));
        log.info("定时备份任务结束......");
    }
}
